<div class="layui-row">
  <div class="layui-col-lg3">
    <div class="layui-form-item">
      
      <div class="layui-inline">
        <button class="layui-btn data_handle_btn" id="add_device_permi" style="display: none;">新增</button>
      </div>
      <div class="layui-inline">
        <button type="button" class="layui-btn" id="device_input_btn"  style="display: none;"><i class="layui-icon" ></i>批量新增</button>
      </div>
      <div class="layui-inline">
        <button class="layui-btn" onclick="out_warehouse()">外借</button>
      </div>
      <div class="layui-inline">
        <button class="layui-btn" onclick="back_warehouse()">归还</button>
      </div>
    </div>
  </div>
  <div class="layui-col-lg9">
    <form class="layui-form layui-form-pane" action="">
      <div class="layui-form-item">
        <div class="layui-inline">
          <div class="layui-input-block">
            <input type="text" id="current_warehouse_name" list="current_warehouse" placeholder="库存位置选择"  autocomplete="off" class="layui-input" onkeyup="show_warehouse_asset(this.value)">
            <datalist id="current_warehouse"></datalist>
          </div>
        </div>
        <div class="layui-inline">
          <!-- <label class="layui-form-label layui-bg-green">品类查询</label> -->
          <div class="layui-input-inline">
            <input type="text" name="asset_kind" list="asset_kind_chose" placeholder="品类选择"  autocomplete="off" class="layui-input" onkeyup="select_asset_kind(this.value,'query')">
            <datalist id="asset_kind_chose"></datalist>
          </div>
        </div>
        <div class="layui-inline">
          <div class="layui-input-inline">
            <input type="text" l name="search_key"  placeholder="编号/名称" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
          <a class="layui-btn" lay-submit="" lay-filter="data-search-btn">搜索</a>
        </div>
      </div>
    </form>
  </div>
</div>

<table class="layui-table" id="base_info_manage_table" lay-filter="base_info_manage_table"></table>

<script type="text/html" id="table_header">
  <p>资产管理表</p>
</script>
<!-- 添加数据表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="handle_data_form" lay-filter="handle_data_form" style="padding: 10px;display: none;">

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">品类</label>
      <div class="layui-input-block">
        <input type="text"  list="leader_kind" name="kind" lay-verify="required" lay-reqtext="必填项!"  placeholder="必选，选择品类"  autocomplete="off" class="layui-input">
        <datalist id="leader_kind"></datalist>
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">名称</label>
      <div class="layui-input-block">
        <input type="text" name="name" placeholder="自定义名称" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">规格描述</label>
      <div class="layui-input-block">
        <input type="text" name="spec"  placeholder="规格描述"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">数量</label>
      <div class="layui-input-block">
        <input type="text" name="number" lay-verify="number" value="1"  placeholder="数量"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">单位</label>
      <div class="layui-input-block">
        <input type="text" name="unit" placeholder="单位"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

   <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">位置</label>
      <div class="layui-input-block">
        <input type="text" name="location" placeholder="手动输入初始位置信息"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item" >
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" >绑定标签ID</label>
      <div class="layui-input-block" >
        <input id="bind_device" name="device_id" type="text" list="bind_device_list"  name="tml_serch"  placeholder="选择设备" autocomplete="off" class="layui-input">
          <datalist id="bind_device_list"></datalist>
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">备注</label>
      <div class="layui-input-block">
        <input type="text" name="remark"  placeholder="备注"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">添加方式</label>
      <div class="layui-input-block">
        <input type="text" name="operate_way" placeholder="单位" value="manu_input"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">状态</label>
      <div class="layui-input-block">
        <input type="text" name="status" placeholder="单位" value="free"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <button class="layui-btn layui-btn-fluid" id="add_submit_btn" lay-submit lay-filter="add_submit" >提交</button>

</form>

<!-- 添加数据表单结束 -->

<!-- 修改数据表单开始 -->

<form  class="layui-form layui-form-pane " action="" id="edit_data_form" lay-filter="edit_data_form" style="padding: 10px;display: none;">

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">品类</label>
      <div class="layui-input-block">
        <input type="text" readonly="" list="change_leader_kind" name="kind"  placeholder="所从属的大类名称"  autocomplete="off" class="layui-input">
        <datalist id="change_leader_kind"></datalist>
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">编号</label>
      <div class="layui-input-block">
        <input type="text" name="unique_id" lay-verify="required" readonly="" lay-reqtext="必填项!" placeholder="必填" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">名称</label>
      <div class="layui-input-block">
        <input type="text" name="name" placeholder="自定义名称" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">规格描述</label>
      <div class="layui-input-block">
        <input type="text" name="spec"  placeholder="规格描述"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">数量</label>
      <div class="layui-input-block">
        <input type="text" name="number" lay-verify="number" value="0"  placeholder="数量"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">位置</label>
      <div class="layui-input-block">
        <input type="text" name="location" placeholder="手动输入位置信息"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">单位</label>
      <div class="layui-input-block">
        <input type="text" name="unit" placeholder="单位"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">状态</label>
      <div class="layui-input-block">
        <input type="text" name="status" placeholder="单位" value="on"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">备注</label>
      <div class="layui-input-block">
        <input type="text" name="remark"  placeholder="备注"  autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item" >
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" >绑定标签ID</label>
      <div class="layui-input-block" >
        <input id="change_device" name="device_id" type="text" list="change_device_list"  name="tml_serch"  placeholder="选择设备" autocomplete="off" class="layui-input">
        <datalist id="change_device_list"></datalist>
      </div>
      <div class="layui-form-mid layui-word-aux"></div>
      <a class="layui-btn layui-btn-sm" onclick="dismiss_dev()">解绑</a>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">使用者</label>
      <div class="layui-input-block">
        <input type="text" list="user_list" name="user" placeholder="资产领用人" autocomplete="off" class="layui-input">
        <datalist id="user_list"></datalist>
      </div>
    </div>
  </div>

  <button class="layui-btn layui-btn-fluid" id="edit_submit_btn" lay-submit lay-filter="edit_submit" >提交</button>

</form>
<!-- 修改数据表单结束 -->

<!-- 设备转移表单 开始-->
<div class="layui-container" id="device_deliver_div" style="display: none;padding: 20px">
    <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" style="text-align: center;">转移到</label>
      <div class="layui-input-block">
       <input type="text" list="deliver_target" name="" class="layui-input" id="dev_to_user">
        <datalist id="deliver_target">
        </datalist>
      </div>
    </div>
  </div>
  <table id="user_tree"  class="layui-table"></table>
</div>
<!-- 设备转移表单 结束-->

<!-- 设备导入处理开始 -->
<div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">id</label>
      <div class="layui-input-block">
        <input type="text" name="device_input"  autocomplete="off" class="layui-input" id="device_input">
      </div>
    </div>
</div>
<!-- 设备导入处理结束 -->

<!-- 引入把上传的表格转变为json的插件 -->
<script src="/static/js/xlsx.js"></script>
<!-- js代码开始 -->

<script type="text/javascript">
console.log(user_permi)
if(user_permi=='superuser'){
  $('#add_device_permi').show()
  $('#device_input_btn').show()
  $('#device_deliver_permi').show()
}
if(user_permi=='代理商'){
  $('#add_device_permi').show()
  $('#device_deliver_permi').show()
}
var ajax_url='asset';
// 设备数据表格渲染函数

var table_show=function(table_data){
  table.render({
    elem: '#base_info_manage_table',
    toolbar:'#table_header',
    data: table_data,
    id:'base_info_manage_table',
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'index', title: '序号',width:50,templet:function(obj){
          return obj.LAY_TABLE_INDEX+1
        }},
        {field: 'kind', title: '品类',sort:true},
        {field: 'name', title: '名称',sort:true},
        {field: 'unique_id', title: '编号',sort:true},
        {field: 'spec', title: '规格',sort:true},
        {field: 'number', title: '数量',sort:true},
        {field: 'unit', title: '单位',sort:true,},
        {field: 'device_id', title: '标签位置',sort:true,templet:function(obj){
          var dev=obj.device_id
          var loca=get_detail_from_id(device,dev)
          if(loca){
            return dev+','+loca.dynamic.location
          }
          return dev
        }},
        {field: 'location', title: '初始位置',sort:true},
        {field: 'status', title: '状态',sort:true,templet:function(obj){
          var val={'free':'空闲','on_use':'使用中','broken':'已报废'}
          return val[obj.status]
          
        }},
        {field: 'owner', title: '操作人',sort:true,templet:function(obj){
          return user_info_objs[obj.owner].visible_name
        }},
        {field: 'remark', title: '备注'},
        {field: 'date_added', title: '创建时间',sort:true},
        {title: '操作', minWidth: 110, templet: function(obj){
          var value=''
          var a='<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>'
          var b='<a class="layui-btn layui-btn-xs layui-btn-normal " lay-event="lend">外借</a>'
          var c='<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="broken">报废</a>'
          var d='<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="back">归还</a>'
          if(obj.status=='free'){
            value=a+b+c
          }else if(obj.status=='on_use'){
            value=d
          }
          return value
        }, fixed: "right", align: "center"}
    ]],
    limits: [10, 15, 20, 25, 50, 100],
    limit: 10,
    page: true
  });
}

// 首次用户数据加载
var asset,asset_kind,dev_data;
var handle_get_func=function(data){
  asset=data.asset
  console.log(asset)
  asset_kind=data.asset_kind
  dev_data=data.dev_data
  table_show(asset)
}
get_info_ajax(ajax_url,'get_init_data',handle_get_func)


// 打开添加操作弹窗
$(".data_handle_btn").on("click", function () {
    document.getElementById("handle_data_form").reset();
    fill_option(dev_data,'bind_device_list','device_id')
    fill_option(asset_kind,'leader_kind','name')
    
    form.render();
    layer.open({
        type: 1
        ,title:'新增资产'
        ,area:'auto'
        ,offset:'100px'  
        ,id: 'add_data' //防止重复弹出
        ,content:$('#handle_data_form')
        ,shade: 0 //不显示遮罩
      });
});

// 监听添加操作,并提交
form.on('submit(add_submit)',function(obj){
  var base_info=package_data(obj.field)
  // 校验品类，防止用户随意输入
  var asset_kind_obj={}
  for(var i=0;i<asset_kind.length;i++){
    asset_kind_obj[asset_kind[i].name]=asset_kind[i]
  }
  if(asset_kind_obj[base_info.kind]==null){
    layer.msg('品类信息错误，请重新选择')
    return false
  }
  // console.log(base_info)
  post_info_ajax(base_info,ajax_url,'add',table_show)
  return false
})


// 监听编辑操作按钮
table.on('tool(base_info_manage_table)', function (obj) {
  var chose_data = obj.data;
  if(obj.event=='edit'){
    document.getElementById("edit_data_form").reset();
    var detail=eval('('+chose_data.detail+')')
    chose_data=$.extend(chose_data,detail)
    form.val('edit_data_form',chose_data)
    // 不允许修改品类
    if(chose_data .device_id!=='' && chose_data .device_id!=='0'){
      $('#change_device').attr('readonly','readonly')
    }else{
      fill_option(dev_data,'change_device_list','device_id')
    }
    if(chose_data.device_id==''){
      dismiss_dev()
    }
    form.render();
    layer.open({
      type: 1
      ,area:'auto'
      ,offset:'60px'  
      ,id: 'edit_data' 
      ,content:$('#edit_data_form')
      ,shade: 0 //不显示遮罩
    }); 
  }else if(obj.event=='lend'){
    console.log(obj)
  }else if(obj.event=='broken'){
    layer.confirm("确定报废："+chose_data.name+"？",
              {btn: ['是', '否']}, 
              function (index) {
                post_info_ajax(chose_data,ajax_url,'del',table_show)
              }
              ,function(){
                console.log('no')
                layer.closeAll()
              });
  }
});

// 监听修改操作,并提交
form.on('submit(edit_submit)',function(obj){
  var base_info=package_data(obj.field)
  console.log(base_info)
  post_info_ajax(base_info,ajax_url,'edit',table_show)
  return false
})

// 解除绑定设备
var dismiss_dev=function(){
  $('#change_device').removeAttr('readonly')
  $('#change_device').val('')

  fill_option(dev_data,'change_device_list','device_id')

}

//封装数据
var package_data=function(data){
  var operate_way=data.operate_way
  delete data.operate_way
  data.detail=JSON.stringify({'operate_way':operate_way})
  return data
}

// 自动生成资产编码
// var create_asset_code=function(name,dom){
//   if(name==''){
//     layer.msg('请选择品类，没有品类请在品类管理创建')
//     return
//   }

//   var asset_code='';
//   var id_list=[];
//   for(var i=0;i<asset_kind.length;i++){
//     if(asset_kind[i].name==name){
//       asset_code=asset_kind[i].name_id
//     }
//   }
//   for(var i=0;i<asset.length;i++){
//     if(asset[i].kind==name){
//       var order_num=asset[i].name.split('-')[1]
//       console.log(order_num)
//       if(parseInt(order_num)!=null){
//         id_list.push(parseInt(order_num))
//       }
//     }
//   }
//   id_list.sort(sortNumber)
//   if(id_list.length==0){
//     id_list=[0]
//   }
//   var num=id_list[0]+1
//   $("#"+dom).val(asset_code+'-'+num.toString())
// }
// 数字从大到小排序函数
// function sortNumber(a,b)
// {
// return b-a
// }


// 获取设备数据表格选中的数据，弹出用户结构弹窗，选择转移的目标用户，提交后台处理
$('.device_deliver').click(function(){
  var device_check=table.checkStatus('base_info_manage_table').data
  if(device_check.length===0){
    layer.msg('请选择需要转移的资产')
    return false
  }
  // 渲染用户树形结构
  tree.render({
    elem: '#user_tree'
    ,data: user_tree
    ,showCheckbox: false  //是否显示复选框
    ,id: 'id'
    ,onlyIconControl:true
    ,isJump: false //是否允许点击节点时弹出新窗口跳转
    ,text: {
            defaultNodeName: '未命名' //节点默认名称
            ,none: '无数据' //数据为空时的提示文本
          }   
    ,click: function(obj){
      var data = obj.data;  //获取当前点击的节点数据
      console.log(data)
      if(data['name']=='all'){
        layer.msg('该选择无效！')
        return false
      }
      $('#dev_to_user').val(data['name'])
    }

  });
  // 加载所有下级用户名称
  for(var i=0;i<user_data.length;i++){
    var user_name_option='<option>'+user_data[i]['visible_name']+'</option>'
    $('#deliver_target').append(user_name_option)
  }
// 弹窗，展示用户树形结构，选择用户，提交后台
  layer.open({
        type: 1
        ,title:'设备转移'
        ,area:['400px','500px']
        ,offset:'100px'  //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
        ,id: 'device_deliver' //防止重复弹出
        ,content:$('#device_deliver_div')
        ,btn: ['提交','关闭']
        ,shade: 0 //不显示遮罩
        ,btn1: function(){
            var result={};
            var target_user=$('#dev_to_user').val()
            if (target_user==''){
              layer.msg('请选择目标用户')
              return false
            }
            var devliver_obj=[]
            for(var i=0;i<device_check.length;i++){
              if(device_check[i]['owner']!==result['target_user']){
                devliver_obj.push(device_check[i]['name'])
              }
            }
            result['name']=devliver_obj
            result['target_user']=target_user

            layer.confirm('确定转移到'+target_user, function (index) {
              console.log(result)
              post_info_ajax(result,ajax_url,'change_owner',table_show)

            })
        }
        ,btn2: function(){
          layer.closeAll();
        }
      });

})


// 监听 导入 按钮
$('#device_input_btn').click(function(){
  var input = document.createElement('input');
  input.type = 'file';

  input.addEventListener('change', function() {
    var file = this.files[0];
    var reader = new FileReader();

    reader.onload = function (e) {
      var data = e.currentTarget.result;
      var wb = XLSX.read(data,{type:'binary'})
      var j_data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
      console.log(j_data)
      if(j_data[0]['__EMPTY']!=null){
        layer.msg('表格出错')
        return false
      }

      var batch_add_data=[];
      for(var i=0;i<j_data.length;i++){
         if(j_data[i]['kind']!==0 && j_data[i]['kind']!=='0'  && j_data[i]['kind']!=='' && j_data[i]['kind']!=null){
          var res=package_data(j_data[i])
          if(res.device_id=='0' | res.device_id==0){
            res.device_id=''
          }
          batch_add_data.push(res)
         }  
      }

      layer.confirm('确定导入'+batch_add_data.length.toString()+'个品类信息', function (index) {
        // console.log(batch_add_data)
        post_info_ajax(batch_add_data,ajax_url,'add_from_file',table_show)
      })
    }
    reader.readAsBinaryString(file)
  })

    input.click();
})


// 监听设备搜索操作
form.on('submit(data-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(asset,search_key,'name_id','name')
    // 表格重载
    table_show(search_result)
  }else{
    table_show(asset)
  }
  return false;
});

</script>